package com.nantai.jiafang.nantaijiafang.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nantai.jiafang.nantaijiafang.IConstant;
import com.nantai.jiafang.nantaijiafang.MyApplication;
import com.nantai.jiafang.nantaijiafang.R;
import com.nantai.jiafang.nantaijiafang.activity.UnReadPushListActivity;
import com.nantai.jiafang.nantaijiafang.bean.FabricBatchInfo;
import com.nantai.jiafang.nantaijiafang.bean.ProductionOrderInfo;
import com.nantai.jiafang.nantaijiafang.utils.Tools;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static com.nantai.jiafang.nantaijiafang.activity.LoginActivity.userId;

/**
 * 信息推送
 */
public class FragMessagePush extends Fragment {

    private RelativeLayout mRlProductionInfo;
    private RelativeLayout mRlfabricbatch;
    private final int INTENT_PRODUCTION_ORDER = 0x1001;
    private final int INTENT_FABRID_BATCH = 0x1002;
    private TextView tv_1;
    private TextView tv_2;
    private ImageView iv_1;
    private ImageView iv_2;
    private DbManager db;
    //同步数据
    private Button btn_update_data;
    private ProgressDialog progressDialog;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_frag_message_push, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        db = x.getDb(MyApplication.daoConfig);
        initViews();
    }

    private void initViews() {
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("正在同步数据");
        tv_1 = (TextView) getView().findViewById(R.id.tv_1);
        tv_2 = (TextView) getView().findViewById(R.id.tv_2);
        iv_1 = (ImageView) getView().findViewById(R.id.iv_1);
        iv_2 = (ImageView) getView().findViewById(R.id.iv_2);
        btn_update_data = (Button) getView().findViewById(R.id.btn_update_data);
        //生产订单利用率信息
        mRlProductionInfo = (RelativeLayout) getView().findViewById(R.id.rl_production_info);
        mRlProductionInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra(IConstant.INTENT, "1");
                intent.setClass(getActivity(), UnReadPushListActivity.class);
                startActivityForResult(intent, INTENT_PRODUCTION_ORDER);
            }
        });
        //面料批次利用率信息
        mRlfabricbatch = (RelativeLayout) getView().findViewById(R.id.rl_febricbatch);
        mRlfabricbatch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), UnReadPushListActivity.class);
                intent.putExtra(IConstant.INTENT, "2");
                startActivityForResult(intent, INTENT_FABRID_BATCH);
            }
        });
        btn_update_data.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //同步数据
                progressDialog.show();
                updateDataFromNet();
            }
        });
        updateNewMessage();
    }

    //同步数据
    private void updateDataFromNet() {

        RequestParams params = new RequestParams("http://222.188.95.94:7065/PushHandler.ashx");
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                progressDialog.dismiss();
                System.out.println("返回结果：" + result);
                Tools.showToast(getActivity(), "数据同步成功");
                anaylysisData(result);
                updateNewMessage();

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Tools.showToast(getActivity(), "数据同步失败");
                progressDialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                progressDialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case INTENT_PRODUCTION_ORDER:

                break;

            case INTENT_FABRID_BATCH:

                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        updateNewMessage();
    }

    //解析获取到的数据
    private void anaylysisData(String result) {
        Gson gson = new Gson();
        try {
            List<String> list_keys = new ArrayList<>();
            JSONObject jo = new JSONObject(result);
            Iterator it_color = jo.keys();
            while (it_color.hasNext()) {
                String key = it_color.next().toString();
                list_keys.add(key);
            }
            System.out.println("key:" + list_keys.size());
            for (int i = 0; i < list_keys.size(); i++) {
                if (list_keys.get(i).contains("ML")) {
                    List<FabricBatchInfo> list_fabric = gson.fromJson(jo.getString(list_keys.get(i)), new TypeToken<List<FabricBatchInfo>>() {
                    }.getType());
                    for (int j = 0; j < list_fabric.size(); j++) {
                        list_fabric.get(j).setIsRead("0");
                        list_fabric.get(j).setUserId(userId);
                    }
                    System.out.println("list1:" + list_fabric.size());
                    insertIntoFabricDB(list_fabric);
                } else if (list_keys.get(i).contains("SCDD")) {
                    List<ProductionOrderInfo> list_production = gson.fromJson(jo.getString(list_keys.get(i)), new TypeToken<List<ProductionOrderInfo>>() {
                    }.getType());
                    for (int j = 0; j < list_production.size(); j++) {
                        list_production.get(j).setIsRead("0");
                        list_production.get(j).setUserId(userId);
                    }
                    System.out.println("list2:" + list_production.size());
                    insertIntoProductionDB(list_production);
                }
            }
            progressDialog.dismiss();
        } catch (JSONException e) {
            System.out.println("GSON出错");
        }
    }

    private void insertIntoFabricDB(List<FabricBatchInfo> list) {
        try {
            FabricBatchInfo info = list.get(0);
            List<FabricBatchInfo> list_db;
            list_db = db.selector(FabricBatchInfo.class).where("Timestamp", "=", info.getTimestamp()).and("userId","=", userId).findAll();
            if (list_db==null||list_db.size()==0){
                System.out.println("插入数量1："+list.size());
                db.save(list);
            }
        } catch (DbException e) {
            System.out.println("插入数据库出错1");
        }
    }

    private void insertIntoProductionDB(List<ProductionOrderInfo> list) {
        try {
            ProductionOrderInfo info = list.get(0);
            List<ProductionOrderInfo> list_db;
            list_db = db.selector(ProductionOrderInfo.class).where("Timestamp", "=", info.getTimestamp()).and("userId","=", userId).findAll();
            if (list_db==null||list_db.size()==0){
                System.out.println("插入数量2："+list.size());
                db.save(list);
            }
        } catch (DbException e) {
            System.out.println("插入数据库出错2");
        }
    }

    public void updateNewMessage() {
        List<ProductionOrderInfo> list1 = new ArrayList<>();
        try {
            list1 = db.selector(ProductionOrderInfo.class).where("isRead", "=", "0").and("userId","=", userId).findAll();
            if (list1 == null) {
                list1 = new ArrayList<>();
            }
            if ((list1.size()) > 0) {
                iv_1.setVisibility(View.VISIBLE);
                tv_1.setVisibility(View.VISIBLE);
                tv_1.setText(((list1.size()) + ""));
            } else {
                tv_1.setVisibility(View.GONE);
                iv_1.setVisibility(View.GONE);
            }
        } catch (DbException e) {

        }

        List<FabricBatchInfo> list2 = new ArrayList<>();
        try {
            list2 = db.selector(FabricBatchInfo.class).where("isRead", "=", "0").and("userId","=", userId).findAll();
            if (list2 == null) {
                list2 = new ArrayList<>();
            }
            if (list2.size() > 0) {
                iv_2.setVisibility(View.VISIBLE);
                tv_2.setVisibility(View.VISIBLE);
                tv_2.setText(((list2.size()) + ""));
            } else {
                tv_2.setVisibility(View.GONE);
                iv_2.setVisibility(View.GONE);
            }
        } catch (DbException e) {

        }

    }
}
